package com.kinon.ceshiaccount.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.bean.PhoneUserBean;
import com.kinon.ceshiaccount.bean.base.Balance;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.urgent.Card;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SoundPoolManage;
import com.kinon.ceshiaccount.util.SysTimeManage;
import com.kinon.ceshiaccount.util.ToastUtil;
import com.kinon.ceshiaccount.view.CustomDialog;

import org.litepal.crud.DataSupport;

import retrofit2.Call;
import retrofit2.Response;
import sunmi.ds.callback.ISendCallback;

/**
 * Created by luohao on 2017-08-01.
 * 结算生成的订单界面，负责刷卡支付
 */

public class OrderPayActivity extends BaseActivity implements View.OnClickListener {
    int diningType;
    ToastUtil toastUtil = new ToastUtil();
    Handler myHandler = new Handler();
    Runnable delayRun = new Runnable() {
        @Override
        public void run() {
            SunmiSdkManage.getInstance().showWelcomeImg();
        }
    };
    /**
     * 返回
     */
    private TextView tv_back;
    /**
     * 显示收款金额
     */
    private TextView tv_orderTotal;
    /**
     * 接收卡号
     */
    private EditText et_pay;
    //手机校验
    private Button btn_checkPhone;
    private String oridrid = "";
    private String total = "0.0";
    private boolean urgent;
    private String detail = "";
    private String nonce_str = "";
    private CustomDialog dialog;
    private String mUserCard = null;
    private ISendCallback callback = new ISendCallback() {
        @Override
        public void onSendSuccess(long taskId) {
            myHandler.postDelayed(delayRun, 1000);
//           SunmiSdkManage.getInstance().showWelcomeImg();
        }

        @Override
        public void onSendFail(int errorId, String errorInfo) {
//           Mtoast("副屏显示失败");
            toastUtil.Short("" + "副屏显示失败")
                    .setToastBackground(Color.WHITE, 0).show();
        }

        @Override
        public void onSendProcess(long totle, long sended) {

        }
    };
    private TextWatcher tWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence text, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence text, int start, int icount, int iafter) {
            if (start == Constant.CARD_LENGTH - 1) {
                String card = text.toString();
                otherPay(card);

            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    private static final int TIME_INTERVAL = 750;
    private long TIME_FIRST = 0L;

    private String orderTimestamp = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderpay_layout);
        initView();
    }

    private void initView() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_orderTotal = (TextView) findViewById(R.id.tv_orderTotal);
        et_pay = (EditText) findViewById(R.id.et_pay);
        btn_checkPhone = (Button) findViewById(R.id.btn_checkPhone);

        if (Constant.URGENT_TYPE) {
            btn_checkPhone.setVisibility(View.GONE);
        }

        total = getIntent().getStringExtra("total");
        oridrid = getIntent().getStringExtra("oridrid");
        diningType = getIntent().getIntExtra("diningType", 0);
        urgent = getIntent().getBooleanExtra("urgent", true);
        detail = getIntent().getStringExtra("orderDetail");
        detail = TextUtils.isEmpty(detail) ? "" : detail;
        nonce_str = getIntent().getStringExtra("nonce_str");

        SunmiSdkManage.getInstance().showDoubleLineImg(getString(R.string.pleasePay),
                String.valueOf(total), null);
        tv_orderTotal.setText(String.valueOf(total));
        tv_back.setOnClickListener(this);
        btn_checkPhone.setOnClickListener(this);
        et_pay.addTextChangedListener(tWatcher);
    }

    private void addSqlite(String card) {
        synchronized (card) {
            int cardnub = DataSupport.where("no = ?", card).count(Card.class);

            if (cardnub < 1) {
                SoundPoolManage.getInstance().soundpPlay(2);
                SunmiSdkManage.getInstance().showPrice("", getString(R.string.pay_failure), callback);
                toastUtil.Short("刷卡过快").setToastBackground(Color.WHITE, 0).show();
//                    Mtoast("刷卡频率过快或付款码无效");
                return;
            }

            long sysTime = System.currentTimeMillis();
            String id = SysTimeManage.getInstage().getOrderId(sysTime);
//			int type = SysTimeManage.getInstage().getOrderType(sysTime);
            String time = SysTimeManage.getInstage().getDateTime(sysTime);
            String date = SysTimeManage.getInstage().getDate(sysTime);
            int ctype = TextUtils.isEmpty(detail) ? 1 : 2;
            U_SettletmentBean settl = new U_SettletmentBean
                    (id, card, diningType, total + "", time, 0, 0, 0, date, 0, nonce_str, ctype, detail);
            boolean save = settl.save();
            if (save) {
                SoundPoolManage.getInstance().soundpPlay(1);
                SunmiSdkManage.getInstance().showPrice("", getString(R.string.pay_success), callback);
//				showBanlance();
                Toast.makeText(getApplicationContext(), "刷卡成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),
                        PayresultActivity.class);
//                intent.putExtra("type", Constant.URGENT_CARD_SUCCESS);
                startActivity(intent);
                finish();
            } else {
                SoundPoolManage.getInstance().soundpPlay(2);
                SunmiSdkManage.getInstance().showPrice("", getString(R.string.pay_failure), callback);
//                Mtoast("刷卡失败");
                toastUtil.Short("刷卡失败").setToastBackground(Color.WHITE, 0).show();
            }
        }
    }

    private void otherPay(String card) {
//        et_pay.setEnabled(false);
        et_pay.setText("");
        if (Constant.URGENT_TYPE || urgent) {
            addSqlite(card);
        } else {
//            payCall(card);
            payV2Call(card);
        }
    }

    private void payCall(String card) {
        Call<String> call = HttpManage.getRequestApi().otherPay(
                SPManage.getInstance().getToken(), oridrid, card, nonce_str, Constant.ACCESS_PAY_TYPE/*,diningType+""*/);
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String base) {
                SoundPoolManage.getInstance().soundpPlay(1);
                et_pay.setEnabled(true);
                //BaseBean<JsonObject> bean=response.body();
                Gson gson = new Gson();

                Balance balanceBean = gson.fromJson(base, Balance.class);
                //Log.e(TAG, "bean.getData()=="+bean.getData().toString() );
                //普通员工
                if (balanceBean.getType() == 0) {
                    SunmiSdkManage.getInstance().showDoubleLineImg("余额", String.valueOf(balanceBean.getBalance()), callback);
                    //临时卡
                } else if (balanceBean.getType() == 1) {
                    SunmiSdkManage.getInstance().showDoubleLineImg(getString(R.string.pay_success),
                            "剩余次数:" + balanceBean.getLeft(), callback);
                }

                Intent intent = new Intent(getApplicationContext(), PayresultActivity.class);
                intent.putExtra("balance", "1");
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int code, String error) {
                SoundPoolManage.getInstance().soundpPlay(2);
                et_pay.setEnabled(true);
//                Mtoast(error);
                toastUtil.Short(error)
                        .setToastBackground(Color.WHITE, 0).show();
                SunmiSdkManage.getInstance().showPrice("", error, callback);
            }
        });
    }

    private void payV2Call(String card) {
        //if (System.currentTimeMillis() - TIME_FIRST > TIME_INTERVAL) {
        //    TIME_FIRST = System.currentTimeMillis();
        //
        //} else {
        //    toastUtil.Short("请勿重复刷卡");
        //}
        if (orderTimestamp.equals(nonce_str)) {
            toastUtil.Short("请勿重复刷卡");
            return;
        }

        orderTimestamp = nonce_str;

        Call<String> call = HttpManage.getRequestApi().otherPay_v2(
                SPManage.getInstance().getToken(),total, card, nonce_str,
                Constant.ACCESS_PAY_TYPE, diningType + "");
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String base) {
                SoundPoolManage.getInstance().soundpPlay(1);
                et_pay.setEnabled(true);
                Gson gson = new Gson();

                Balance balanceBean = gson.fromJson(base, Balance.class);
//                Log.e(TAG, "bean.getData()=="+bean.getData().toString() );
                //普通员工
                if (balanceBean.getType() == 0) {
                    SunmiSdkManage.getInstance().showDoubleLineImg("余额",
                            String.valueOf(balanceBean.getBalance()), callback);
                    //临时卡
                } else if (balanceBean.getType() == 1) {
                    SunmiSdkManage.getInstance().showDoubleLineImg(getString(R.string.pay_success),
                            "剩余次数:" + balanceBean.getLeft(),
                            callback);
                }

                Intent intent = new Intent(getApplicationContext(), PayresultActivity.class);
                intent.putExtra("balance", "1");
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int code, String error) {
                SoundPoolManage.getInstance().soundpPlay(2);
                et_pay.setEnabled(true);
//                Mtoast(error);
                toastUtil.Short(error)
                        .setToastBackground(Color.WHITE, 0).show();
                SunmiSdkManage.getInstance().showPrice("", error, callback);
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                if (!Constant.URGENT_TYPE) {
                    //cancelOrder();
                    finish();
                } else {
                    SunmiSdkManage.getInstance().showWelcomeImg();
                    finish();
                }
                break;
            case R.id.btn_checkPhone:
                if (urgent) {
//                    Mtoast("网络不稳定不能使用手机号支付," +
//                            "请刷卡或重新生成订单");
                    toastUtil.Short("网络不稳定不能使用手机号支付," +
                            "请刷卡或重新生成订单").setToastBackground(Color.WHITE, 0).show();
                    return;
                }
                dialog = new CustomDialog(2, OrderPayActivity.this, new CustomDialog.DialogClickListener() {
                    @Override
                    public void onDialogClick(int btn) {
                        if (btn == 1) {
                            if (TextUtils.isEmpty(mUserCard)) {
                                phoneCheckInfo();
                            } else {
                                otherPay(mUserCard);
                            }
                        }
                    }
                });
                dialog.show();
                break;
                default:
                    break;
        }
    }

    private void phoneCheckInfo() {

        Call<String> call = HttpManage.getRequestApi().phoneCheck
                (SPManage.getInstance().getToken(), dialog.getPhone());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                Gson gson = new Gson();
                PhoneUserBean user = gson.fromJson(data, PhoneUserBean.class);
                mUserCard = user.getNo();
                dialog.setmStrMsg("姓名：" + user.getName() + "\n手机："
                        + user.getUsername() + "\n卡号：" + mUserCard);
                dialog.setmType(1);

            }

            @Override
            public void onError(int code, String error) {
                dialog.setmStrMsg(error + "");
                dialog.setmType(1);
            }
        });
    }


    @Override
    public void onBackPressed() {
        //cancelOrder();
        super.onBackPressed();
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        Call<BaseBean<String>> call = HttpManage.getRequestApi().cancelOrder(
                SPManage.getInstance().getToken(), oridrid);

        call.enqueue(new MyCallback<BaseBean<String>>() {
            @Override
            public void onSuccess(Call<BaseBean<String>> call, Response<BaseBean<String>> response) {
            }

            @Override
            public void onError(int code, String error) {
            }
        });

        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        SunmiSdkManage.getInstance().showWelcomeImg();
    }
}
